<template>
  <div class="table-container">
    <el-table 
      :data="tableData" 
      style="width: 100%"
      :header-cell-style="{
        background: '#f5f7fa',
        color: '#606266',
        textAlign: 'center',
        fontWeight: 'bold'
      }"
      :cell-style="{ textAlign: 'center' }"
      v-loading="loading">
      <el-table-column 
        prop="date" 
        label="日期" 
        min-width="120"
        align="center"
        show-overflow-tooltip>
        <template #default="scope">
          {{ formatDate(scope.row.date) }}
        </template>
      </el-table-column>
      <el-table-column 
        prop="period" 
        label="时间段" 
        min-width="120"
        align="center"
        show-overflow-tooltip>
        <template #default="scope">
          {{ getPeriodLabel(scope.row.period) }}
        </template>
      </el-table-column>
      <el-table-column 
        prop="status" 
        label="状态" 
        min-width="120"
        align="center"
        show-overflow-tooltip>
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column 
        label="操作" 
        min-width="120"
        align="center"
        fixed="right">
        <template #default="scope">
          <el-button
            v-if="scope.row.status === 0"
            type="danger"
            link
            :disabled="scope.row.status !== 0"
            @click="handleDelete(scope.row)">
            取消排班
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserInfoStore } from '@/stores/info'
import ScheduleApi from '@/api/schedual'
import type { Schedule } from '@/api/schedual/types'


const userInfoStore = useUserInfoStore()
const loading = ref(false)
const tableData = ref<Schedule[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 时间段映射
const periodMap: Record<number, string> = {
  1: '8：00-8：50',
  2: '9：00-9：50',
  3: '10：00-10：50',
  4: '11：00-11：50',
  5: '14：00-14：50',
  6: '15：00-15：50',
  7: '16：00-16：50'
}

// 状态映射
interface StatusType {
  label: string
  type: 'success' | 'warning' | 'info' | 'danger'
}

const statusMap: Record<number, StatusType> = {
  0: { label: '可预约', type: 'success' },
  1: { label: '已预约', type: 'info' },
}

// 格式化日期
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr)
  return date.toISOString().split('T')[0]
}

// 获取时间段标签
const getPeriodLabel = (period: number) => {
  return periodMap[period] || '未知时间段'
}

// 获取状态标签
const getStatusLabel = (status: number) => {
  return statusMap[status]?.label || '未知状态'
}

// 获取状态类型
const getStatusType = (status: number) => {
  return statusMap[status]?.type || ''
}

// 检查并删除过期时间段
const checkExpiredSlots = async (schedules: Schedule[]) => {
  const now = new Date()
  const expiredSlots = schedules.filter(slot => {
    if (!slot.date || !slot.period) return false
    
    const slotDate = new Date(slot.date)
    const periodEndTimes: Record<number, number> = {
      1: 8.83,  // 8:50
      2: 9.83,  // 9:50
      3: 10.83, // 10:50
      4: 11.83, // 11:50
      5: 14.83, // 14:50
      6: 15.83, // 15:50
      7: 16.83  // 16:50
    }
    
    // 设置时间
    slotDate.setHours(Math.floor(periodEndTimes[slot.period]))
    slotDate.setMinutes((periodEndTimes[slot.period] % 1) * 60)
    
    return slotDate < now
  })

  // 批量删除过期时间段
  if (expiredSlots.length > 0) {
    try {
      const deletePromises = expiredSlots.map(slot => {
        if (slot.time_id) {
          return ScheduleApi.deleteSchedule(slot.time_id)
        }
      })
      
      await Promise.all(deletePromises)
    } catch (error) {
      console.error('删除过期时间段失败:', error)
    }
  }
}

// 获取排班列表
const getScheduleList = async () => {
  loading.value = true
  try {
    const res = await ScheduleApi.getSchedules({
      user_id: userInfoStore.userInfo.user_id,
      Page: currentPage.value,
      Size: pageSize.value,
      is_delete: 0
    })
    
    if (res) {
      if (Array.isArray(res.data)) {
        // 先检查并删除过期时间段
        await checkExpiredSlots(res.data)
        
        // 重新获取最新数据
        const updatedRes = await ScheduleApi.getSchedules({
          user_id: userInfoStore.userInfo.user_id,
          Page: currentPage.value,
          Size: pageSize.value,
          is_delete: 0
        })
        
        if (updatedRes && Array.isArray(updatedRes.data)) {
          tableData.value = updatedRes.data
          total.value =  updatedRes.data.length
        }
      }
    } else {
      ElMessage.error('获取排班列表失败')
    }
  } catch (error) {
    console.error('获取排班列表失败:', error)
    ElMessage.error('获取排班列表失败')
  } finally {
    loading.value = false
  }
}

// 修改定时器类型定义
let checkInterval: ReturnType<typeof setInterval> | null = null

onMounted(() => {
  getScheduleList()
  
  // 设置定期检查
  checkInterval = setInterval(() => {
    if (tableData.value.length > 0) {
      checkExpiredSlots(tableData.value)
        .then(() => getScheduleList())
        .catch(error => console.error('定期检查过期时间段失败:', error))
    }
  }, 3600000) // 每小时检查一次
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (checkInterval) {
    clearInterval(checkInterval)
    checkInterval = null
  }
})

// 删除排班
const handleDelete = async (row: Schedule) => {
  if (!row.time_id) {
    ElMessage.error('无效的排班记录')
    return
  }
  try {
    await ElMessageBox.confirm('确定要取消该时间段的排班吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const res = await ScheduleApi.deleteSchedule(row.time_id)
    if (res) {
      ElMessage.success('取消排班成功')
      getScheduleList()
    } else {
      ElMessage.error('取消排班失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消排班失败:', error)
      ElMessage.error('取消排班失败')
    }
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  getScheduleList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getScheduleList()
}
</script>

<style scoped>
.table-container {
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-table) {
  width: 100% !important;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}

:deep(.el-table .cell) {
  white-space: nowrap;
  padding: 8px;
}

:deep(.el-button--primary.is-link) {
  color: #409EFF;
}

:deep(.el-button--danger.is-link) {
  color: #F56C6C;
}

:deep(.el-tag) {
  margin: 0 2px;
}
</style>